package com.wf.DouDiZhuOL.net.http;

import com.wf.DouDiZhuOL.MainFrame;
import com.wf.DouDiZhuOL.Router;
import com.wf.DouDiZhuOL.ServerUnit;
import com.wf.DouDiZhuOL.Tools.Tools;
import com.wf.DouDiZhuOL.task.ExecutorPool;
import com.wf.DouDiZhuOL.util.Constants;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;

public class HttpInHandlerImp {	
	public void channelRead(final ChannelHandlerContext _ctx, final Object msg) 
	{
		/** work线程的内容转交线程池管理类处理，缩短work线程耗时 **/
		ExecutorPool.getInstance().execute(new Runnable() {
			@SuppressWarnings("deprecation")
			public void run() {
				if(ServerUnit.serverRunning)
				{
					FullHttpRequest req = (FullHttpRequest) msg;
					MainFrame.setText("================" + req.method());
					if(req.method() == HttpMethod.GET) // 处理get请求
					{ 
//						getHandle(ctx, req);
						Tools.writeToastMsg(_ctx, Constants.TOAST_MSG_NORMAL, "数据请求错误");
					}
					if (req.method() == HttpMethod.POST) // 处理POST请求
					{ 
						postHandle(_ctx, req);
					}
				}else 
				{
					
				}
			}
		});
	}
	
	private void postHandle(final ChannelHandlerContext _ctx, final FullHttpRequest req) 
	{
		HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);
//		
		try {
			InterfaceHttpData reqType = decoder.getBodyHttpData(Constants.REQ_TYPE);
			InterfaceHttpData reqData = decoder.getBodyHttpData(Constants.REQ_DATA);
			if(reqType != null) 
			{
				int reqTypeInt = Integer.parseInt(((Attribute)reqType).getValue());
				String reqDataValue = "";
				if(reqData != null)
				{
					reqDataValue = ((Attribute)reqData).getValue();
				}
				Router.getInstance().route(reqTypeInt, reqDataValue, _ctx);
			}else
			{
				Tools.writeToastMsg(_ctx, Constants.TOAST_MSG_NORMAL, "数据请求错误");
			}
		} catch (Exception e)
		{
			Tools.writeToastMsg(_ctx, Constants.TOAST_MSG_NORMAL, "数据异常" + e.getMessage());
			e.printStackTrace();
		}
	}
	
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
	{
		
	}
}
